package net.hekka.canyoutalk.web.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.hekka.canyoutalk.data.constant.ErrorCode;
import net.hekka.canyoutalk.data.vo.list.PhoneBookVoList;
import net.hekka.canyoutalk.share.property.RequestParameterProperties;
import net.hekka.canyoutalk.web.processor.PhoneBookProcessor;
import net.hekka.canyoutalk.web.vo.PageVo;

/**
 *
 * @author jeffreyha
 */
public class PhoneBookServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        System.setProperty("file.encoding", "utf-8");
        request.setCharacterEncoding("utf-8");

        //파라메터 받아오는 requestParameterProperties
        RequestParameterProperties requestParameterProperties = getRequestParameterProperties(request);

        String serviceId = requestParameterProperties.getProperty("serviceId");
        System.out.println("serviceId : [" + serviceId + "]");

        System.out.println("requestParameterProperties : [" + requestParameterProperties.toString() + "]");

        if ("getPhoneBookManager".equals(serviceId)) {
            System.out.println("# getPhoneBookManager is called.");
            int errorCode = getPhoneBookManager(request, requestParameterProperties);
            if (errorCode == ErrorCode.SUCCESS) {
                System.out.println("[[getPhoneBookManager]] requestParameterProperties [" + requestParameterProperties.toString() + "]");
                request.getRequestDispatcher("./phoneBookManager.jsp").forward(request, response);
            } else if (errorCode == ErrorCode.PHONEBOOKSERVLET_LIST_IS_NOT_EXIST) {
                System.out.println("[getPhoneBookManager ERR] phoneBookManager.jsp call...[" + errorCode + "]");
                request.getRequestDispatcher("./phoneBookManager.jsp").forward(request, response);
            } else {
                System.out.println("[getPhoneBookManager ERR] phoneBookManager.jsp call...[" + errorCode + "]");
                response.sendRedirect("system/canyoutalk_error001.jsp");  // Go to Fail Page.
            }
        } else if ("addPhoneBook".equals(serviceId)) {
            System.out.println("# addPhoneBook is called.");
            int returnValue = addPhoneBook(request, requestParameterProperties);
            request.setAttribute("returnValue", Integer.toString(returnValue) );

            System.out.println("[[addPhoneBook]] requestParameterProperties [" + requestParameterProperties.toString() + "]");
            request.getRequestDispatcher("./phoneBookResult.jsp").forward(request, response);

        } else if ("modifyPhoneBook".equals(serviceId)) {
            System.out.println("# modifyPhoneBook is called.");
            int returnValue = modifyPhoneBook(request, requestParameterProperties);
            request.setAttribute("returnValue", Integer.toString(returnValue) );

            System.out.println("[[modifyPhoneBook]] requestParameterProperties [" + requestParameterProperties.toString() + "]");
            request.getRequestDispatcher("./phoneBookResult.jsp").forward(request, response);
        } else if ("erasePhoneBook".equals(serviceId)) {
            System.out.println("# erasePhoneBook is called.");
            int returnValue = erasePhoneBook(request, requestParameterProperties);
            request.setAttribute("returnValue", Integer.toString(returnValue) );

            System.out.println("[[erasePhoneBook]] requestParameterProperties [" + requestParameterProperties.toString() + "]");
            request.getRequestDispatcher("./phoneBookResult.jsp").forward(request, response);
        } else if ("getPhoneBookList".equals(serviceId)) {
            System.out.println("# getPhoneBookList is called.");
            int errorCode = getPhoneBookList(request, requestParameterProperties);
            if (errorCode == ErrorCode.SUCCESS) {
                System.out.println("[[getPhoneBookList]] requestParameterProperties [" + requestParameterProperties.toString() + "]");
                request.getRequestDispatcher("./phoneBookList.jsp").forward(request, response);
            } else if (errorCode == ErrorCode.PHONEBOOKSERVLET_LIST_IS_NOT_EXIST) {
                System.out.println("[getPhoneBookList ERR] phoneBookList.jsp call...[" + errorCode + "]");
                request.getRequestDispatcher("./phoneBookList.jsp").forward(request, response);
            } else {
                System.out.println("[getPhoneBookList ERR] phoneBookList.jsp call...[" + errorCode + "]");
                response.sendRedirect("system/canyoutalk_error001.jsp");  // Go to Fail Page.
            }
        } 
    }

    /**
     * Requst객체의 Parameters의 값을 저장한 Properties객체를 구한다.
     * @param httpServletRequest Request객체
     * @return Requst객체의 Parameters의 값을 저장한 Properties객체
     */
    private RequestParameterProperties getRequestParameterProperties(HttpServletRequest httpServletRequest) {
        RequestParameterProperties requestParameterPropeties = new RequestParameterProperties();
        Enumeration params = httpServletRequest.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = (String) params.nextElement();
            String paramValue = httpServletRequest.getParameter(paramName);
            requestParameterPropeties.put(paramName, paramValue);
        }
        return requestParameterPropeties;
    }

    private int getPhoneBookManager(HttpServletRequest request, RequestParameterProperties requestParameterProperties) {
        int errorCode = ErrorCode.SUCCESS;
        System.out.println("[getPhoneBookManager] " + requestParameterProperties.toString());

        return errorCode;
    }

    private int addPhoneBook(HttpServletRequest request, RequestParameterProperties requestParameterProperties) {
        int errorCode = ErrorCode.SUCCESS;
        System.out.println("[addPhoneBook] " + requestParameterProperties.toString());

        PhoneBookProcessor phoneBookProcessor = new PhoneBookProcessor();
        errorCode = phoneBookProcessor.addPhoneBook(requestParameterProperties);
        return errorCode;
    }

    private int getPhoneBookList(HttpServletRequest httpServletRequest, RequestParameterProperties requestParameterProperties) {
        int errorCode = ErrorCode.SUCCESS;
        PhoneBookProcessor phoneBookProcessor = new PhoneBookProcessor();
        boolean isExist = requestParameterProperties.containsKey("totalCount");
        if (isExist == false) {
            int totalCount = phoneBookProcessor.getCountOfPhoneBook();
            System.out.println("totalCount [" + totalCount + "]");
            requestParameterProperties.put("totalCount", Integer.toString(totalCount));
        }

        Hashtable hashtable = phoneBookProcessor.getPhoneBookList(requestParameterProperties);
        PhoneBookVoList phoneBookVoList = (PhoneBookVoList) hashtable.get("phoneBookVoList");
        PageVo pageVo = (PageVo) hashtable.get("pageVo");
        if (phoneBookVoList == null) {
            errorCode = ErrorCode.PHONEBOOKSERVLET_LIST_IS_NULL;
        } else {
            if (phoneBookVoList.size() == 0) {
                errorCode = ErrorCode.PHONEBOOKSERVLET_LIST_IS_NOT_EXIST;
                httpServletRequest.setAttribute("totalCount", "0");
            } else {
                httpServletRequest.setAttribute("phoneBookVoList", phoneBookVoList);
                httpServletRequest.setAttribute("pageVo", pageVo);
                httpServletRequest.setAttribute("queryCount", requestParameterProperties.getProperty("queryCount"));
                httpServletRequest.setAttribute("nowPage", requestParameterProperties.getProperty("nowPage"));
                httpServletRequest.setAttribute("totalCount", requestParameterProperties.getProperty("totalCount"));
            }
        }
        return errorCode;
    }
    
    private int modifyPhoneBook(HttpServletRequest request, RequestParameterProperties requestParameterProperties) {
        int errorCode = ErrorCode.SUCCESS;
        System.out.println("[modifyPhoneBook] " + requestParameterProperties.toString());

        PhoneBookProcessor phoneBookProcessor = new PhoneBookProcessor();
        errorCode = phoneBookProcessor.modifyPhoneBook(requestParameterProperties);
        return errorCode;
    }

    private int erasePhoneBook(HttpServletRequest request, RequestParameterProperties requestParameterProperties) {
        int errorCode = ErrorCode.SUCCESS;
        System.out.println("[erasePhoneBook] " + requestParameterProperties.toString());

        PhoneBookProcessor phoneBookProcessor = new PhoneBookProcessor();
        errorCode = phoneBookProcessor.erasePhoneBook(requestParameterProperties);
        return errorCode;
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
